const userService = require("../service/user.server");
const fileService = require("../service/file.server");

const fs = require("fs");
const { AVATAR_PATH } = require("../constant/index");

class UserController {
  //创建用户
  async create(ctx, next) {
    //1.获取用户传递过来的信息
    const user = ctx.request.body;

    //2.写入数据库
    const res = await userService.create(user);

    //3.查通知前端创建成功
    ctx.body = {
      message: `用户创建成功~`,
      data: res,
    };
  }

  // 头像信息
  async avatarInfo(ctx, next) {
    // 1.用户的头像是哪一个文件呢?
    const { userId } = ctx.params;
    const avatarInfo = await fileService.getAvatarByUserId(userId);

    // 2.提供图像信息
    ctx.response.set("content-type", avatarInfo.mimetype);
    ctx.body = fs.createReadStream(`${AVATAR_PATH}/${avatarInfo.filename}`);
  }
}

module.exports = new UserController();
